package lancooPaperRateSelf;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.IdRes;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import com.example.lancooznbk.R;
import com.example.lancooznbk.presenter.PaperDef;

import lancooControl.Control;
import lancooControl.CustomRateFillView;
import lancooControl.CustomRateSetScore;

import static testPaperCTCS.GuessTestingPaperActivity.InforGuessTesting;
import static testPaperJBFX.BasicReviewPaperActivity.InforBasicReview;
import static testPaperNDFX.DifficultReviewPaperActivity.InforDifficultReview;
import static testPaperWrong.WrongQuesPaperActivity.InforWrongQues;

/**
 * Created by Administrator on 2017/9/25/025.
 */

public class RateDwtkAdapter extends BaseAdapter {


    private Context mContext;
    private LayoutInflater mInflater;
    private int SumItem;
    private int PaperID;
    private int ModelFrom;//试卷来源

    private ViewHolder holder = null;

    public final class ViewHolder {
        LinearLayout LayoutRate;
        private ViewHolder(View convertView) {
            LayoutRate = (LinearLayout) convertView.findViewById(R.id.layout_rate);
        }

    }

    public RateDwtkAdapter(Context context, int sumItem, int paperID, int modelFrom) {
        this.mContext = context;
        mInflater = LayoutInflater.from(context);
        this.SumItem = sumItem;
        this.PaperID = paperID;
        this.ModelFrom = modelFrom;
    }

    @Override
    public int getCount() {
        return SumItem;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.adapter_rate_dwtk_item, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        /*
        * 获取试题相关信息
        * */
        getQuesInfor();

        /*
        * 显示试题相关信息及实现作答流程
        * */
        showQuesInfor();


        return convertView;
    }

    /*
    * 获取试题相关信息
    * */
    int totalItemCount;
    double score;
    String[] answer;
    String[] stuAnswer;
    String[] stuAssess;
    private void getQuesInfor(){
        if(ModelFrom== PaperDef.FROM_BASE_REVIEW){

            totalItemCount = InforBasicReview.getPaperContent().get(PaperID).getTotalItemCount();

            answer = new String[totalItemCount];
            stuAnswer = new String[totalItemCount];
            stuAssess = new String[totalItemCount];
            for(int i=0;i<totalItemCount;i++){
                answer[i] = new String();
                answer[i] = InforBasicReview.getPaperContent().get(PaperID).getQueList().get(i).getAnswer();
                stuAnswer[i] = new String();
                stuAnswer[i] = InforBasicReview.getPaperContent().get(PaperID).getQueList().get(i).getStuAnswer();
                stuAssess[i] = new String();
                stuAssess[i] = InforBasicReview.getPaperContent().get(PaperID).getQueList().get(i).getStuAssess();
            }

        }else if(ModelFrom==PaperDef.FROM_DIFFERENT_REVIEW){
            totalItemCount = InforDifficultReview.getTotalItemCount();

            answer = new String[totalItemCount];
            stuAnswer = new String[totalItemCount];
            stuAssess = new String[totalItemCount];
            for(int i=0;i<totalItemCount;i++){
                answer[i] = new String();
                answer[i] = InforDifficultReview.getQueList().get(i).getAnswer();
                stuAnswer[i] = new String();
                stuAnswer[i] = InforDifficultReview.getQueList().get(i).getStuAnswer();
                stuAssess[i] = new String();
                stuAssess[i] = InforDifficultReview.getQueList().get(i).getStuAssess();
            }
        }else if(ModelFrom==PaperDef.FROM_GUESS_REVIEW){
            totalItemCount = InforGuessTesting.getPaperContent().get(PaperID).getTotalItemCount();
            score = InforGuessTesting.getPaperContent().get(PaperID).getScore();

            answer = new String[totalItemCount];
            stuAnswer = new String[totalItemCount];
            stuAssess = new String[totalItemCount];
            for(int i=0;i<totalItemCount;i++){
                answer[i] = new String();
                answer[i] = InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(i).getAnswer();
                stuAnswer[i] = new String();
                stuAnswer[i] = InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(i).getStuAnswer();
                stuAssess[i] = new String();
                stuAssess[i] = InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(i).getStuAssess();
            }
        }else if(ModelFrom==PaperDef.FROM_BASE_REVIEW_WRONG||ModelFrom==PaperDef.FROM_DIFFERENT_REVIEW_WRONG){

            totalItemCount = InforWrongQues.get(PaperID).getTotalItemCount();

            answer = new String[totalItemCount];
            stuAnswer = new String[totalItemCount];
            stuAssess = new String[totalItemCount];
            for(int i=0;i<totalItemCount;i++){
                answer[i] = new String();
                answer[i] = InforWrongQues.get(PaperID).getQueList().get(i).getAnswer();
                stuAnswer[i] = new String();
                stuAnswer[i] = InforWrongQues.get(PaperID).getQueList().get(i).getStuAnswer();
                stuAssess[i] = new String();
                stuAssess[i] = InforWrongQues.get(PaperID).getQueList().get(i).getStuAssess();
            }
        }
    }


    public class MyWatcher implements TextWatcher {
        private int beforeDot;
        private int afterDot;
        private int position;
        /**
         * 构造器
         *
         * @param beforeDot 小数点前位数   不限制输入-1
         * @param afterDot  小数点后位数   不限制输入-1
         */
        public MyWatcher(int beforeDot, int afterDot,int position) {
            this.beforeDot = beforeDot;
            this.afterDot = afterDot;
            this.position = position;
        }


        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            Log.e("====ssss===","==0000==="+s.toString());
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.e("====ssss===","==1111==="+s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            judge(s);
            String strAssess = s.toString();

            if(!strAssess.equals("")){
                if(!strAssess.equals("0")){
                    if(strAssess.endsWith(".")){
                        strAssess = strAssess + "0";
                    }else{
                        if(!strAssess.contains(".")){
                            strAssess=strAssess+".0";
                        }
                    }
                }else{
                    strAssess = "0.0";
                }
            }


            setStuAssess(strAssess,position);
        }

        @SuppressLint("NewApi")
        private void judge(Editable editable) {
            String temp = editable.toString();
            double thisScore = score / totalItemCount;

            if(temp.contains(".")){
                if(Control.getStringFrequency(temp,".")==1){

                    if(temp.indexOf(".")!=temp.length()-1&&!temp.contains("..")) {
                        if (Double.valueOf(temp) > thisScore) {
                            Log.e("===editable====","==00111111==");
                            editable.clear();
                            editable.insert(0, String.valueOf(thisScore));
                            return;
                        }else if(Double.valueOf(temp) < thisScore){
                            Log.e("===xxxxxxx====","==xxxxxxx000=="+temp.substring(temp.indexOf(".")+1));
                            if(!temp.endsWith("5")){

                                if(temp.endsWith("6")||temp.endsWith("7")||temp.endsWith("8")||temp.endsWith("9")){
                                    Double dTemp = (double) Math.rint(Double.valueOf(temp));
                                    temp = String.valueOf(dTemp);
                                    editable.clear();
                                    editable.insert(0, String.valueOf(Double.valueOf(temp)));
                                }else {
                                    if(!temp.equals("0.0")){
                                        int iTemp = (int) Math.floor(Double.valueOf(temp));
                                        temp = String.valueOf(iTemp);
                                        editable.clear();
                                        editable.insert(0, String.valueOf(Double.valueOf(temp)));
                                    }
                                }
                                return;
                            }
                        }
                    }

                }
            }else{
                if (!temp.equals("")&&Double.valueOf(temp) > thisScore) {
                    Log.e("===editable====","==0022222==");
                    editable.clear();
                    editable.insert(0, String.valueOf(thisScore));
                    return;
                }
            }


            int posDot = temp.indexOf(".");
            //直接输入小数点的情况
            if (posDot == 0) {
                editable.insert(0, "0");
                return;
            }
            //连续输入0
            if (temp.equals("00")) {
                editable.delete(1, 2);
                return;
            }

            //连续输入.
            if (temp.contains("..")) {
                editable.delete(temp.length()-1, temp.length());
                return;
            }

            //输入"08" 等类似情况
            if (temp.startsWith("0") && temp.length() > 1 && (posDot == -1 || posDot > 1)) {
                editable.delete(0, 1);
                return;
            }

            //不包含小数点 不限制小数点前位数
            if (posDot < 0 && beforeDot == -1) {
                //do nothing 仅仅为了理解逻辑而已
                return;
            } else if (posDot < 0 && beforeDot != -1) {
                //不包含小数点 限制小数点前位数
                if (temp.length() <= beforeDot) {
                    //do nothing 仅仅为了理解逻辑而已
                } else {
                    editable.delete(beforeDot, beforeDot + 1);
                }
                return;
            }

            //如果包含小数点 限制小数点后位数
            if (temp.length() - posDot - 1 > afterDot && afterDot != -1) {
                editable.delete(posDot + afterDot + 1, posDot + afterDot + 2);//删除小数点后多余位数
            }

        }
    }


    /*
    * 显示试题相关信息及实现作答流程
    * */
    private CustomRateSetScore[] RateScore;
    private CustomRateFillView[] RateFill;
    private void showQuesInfor(){

        if(ModelFrom==PaperDef.FROM_GUESS_REVIEW){

            RateScore = new CustomRateSetScore[totalItemCount];
            for(int i=0;i<totalItemCount;i++){
                RateScore[i] = new CustomRateSetScore(mContext);
                RateScore[i].setRateScore(i+1,answer[i],stuAssess[i]);

                final int finalI = i;
                if(stuAssess[i].equals("")){
                    RateScore[i].EdtScore.setHint("请输入评分(总分"+score/totalItemCount+"分，输入为0.5的整数倍)");
                }else {
                    RateScore[i].EdtScore.setSelection(RateScore[i].EdtScore.getText().toString().length());
                }

                RateScore[i].EdtScore.addTextChangedListener(new MyWatcher(-1,1,finalI));

                holder.LayoutRate.addView(RateScore[i]);
            }

        }else{

            RateFill = new CustomRateFillView[totalItemCount];
            for(int i=0;i<totalItemCount;i++){
                RateFill[i] = new CustomRateFillView(mContext);
                RateFill[i].setRateFill(i+1,answer[i],stuAssess[i]);

                final int finalI = i;
                RateFill[i].Rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                        if(checkedId==RateFill[finalI].RbTrue.getId()){
                            setStuAssess("正确",finalI);
                        }else if(checkedId==RateFill[finalI].RbFalse.getId()){
                            setStuAssess("错误",finalI);
                        }
                    }
                });

                holder.LayoutRate.addView(RateFill[i]);
            }

        }


    }

    /*
    * 重新写入当前自评结果
    * */
    private void setStuAssess(String stuAssess,int position){

        if(ModelFrom== PaperDef.FROM_BASE_REVIEW){
            InforBasicReview.getPaperContent().get(PaperID).getQueList().get(position).setStuAssess(stuAssess);

            int totalItemCount = InforBasicReview.getPaperContent().get(PaperID).getTotalItemCount();
            String stuAnswerAll = "";
            String stuAssessAll = "";
            int totalItemCountTrue = 0;
            String thisStuAnswer = "";
            String thisAnswer = "";
            String thisStuAssess = "";
            int quesAnsweredItemCount = 0;
            for(int i=0;i<totalItemCount;i++){
                if(i==0){
                    stuAnswerAll = InforBasicReview.getPaperContent().get(PaperID).getQueList().get(i).getStuAnswer();
                    stuAssessAll = InforBasicReview.getPaperContent().get(PaperID).getQueList().get(i).getStuAssess();
                }else{
                    stuAnswerAll = stuAnswerAll+"#$*#"+InforBasicReview.getPaperContent().get(PaperID).getQueList().get(i).getStuAnswer();
                    stuAssessAll = stuAssessAll+"#$*#"+InforBasicReview.getPaperContent().get(PaperID).getQueList().get(i).getStuAssess();
                }
                thisStuAnswer = InforBasicReview.getPaperContent().get(PaperID).getQueList().get(i).getStuAnswer();
                thisAnswer = InforBasicReview.getPaperContent().get(PaperID).getQueList().get(i).getAnswer();
                thisStuAssess = InforBasicReview.getPaperContent().get(PaperID).getQueList().get(i).getStuAssess();
                if(!thisStuAssess.equals("")) {
                    if (thisStuAssess.equals("正确") || thisStuAssess.equals("优秀")|| thisStuAssess.equals("一般")) {
                        totalItemCountTrue++;
                    }
                }else {
                    if (thisStuAnswer.equals(thisAnswer)) {
                        totalItemCountTrue++;
                    }
                }

                if(!thisStuAnswer.equals("")||!thisStuAssess.equals("")){
                    quesAnsweredItemCount++;
                }

            }

            InforBasicReview.getPaperContent().get(PaperID).setStuAnswerNewAll(stuAnswerAll);
            InforBasicReview.getPaperContent().get(PaperID).setStuAssessNewAll(stuAssessAll);
            InforBasicReview.getPaperContent().get(PaperID).setCorrectRate(Control.getCorrectRate(Float.valueOf(totalItemCountTrue),Float.valueOf(totalItemCount)));
            InforBasicReview.getPaperContent().get(PaperID).setAnsweredItemCount(quesAnsweredItemCount);

        }else if(ModelFrom==PaperDef.FROM_DIFFERENT_REVIEW){
            InforDifficultReview.getQueList().get(position).setStuAssess(stuAssess);

            int totalItemCount = InforDifficultReview.getTotalItemCount();
            String stuAnswerAll = "";
            String stuAssessAll = "";
            int totalItemCountTrue = 0;
            String thisStuAnswer = "";
            String thisAnswer = "";
            String thisStuAssess = "";
            int quesAnsweredItemCount = 0;
            for(int i=0;i<totalItemCount;i++){
                if(i==0){
                    stuAnswerAll = InforDifficultReview.getQueList().get(i).getStuAnswer();
                    stuAssessAll = InforDifficultReview.getQueList().get(i).getStuAssess();
                }else{
                    stuAnswerAll = stuAnswerAll+"#$*#"+InforDifficultReview.getQueList().get(i).getStuAnswer();
                    stuAssessAll = stuAssessAll+"#$*#"+InforDifficultReview.getQueList().get(i).getStuAssess();
                }
                thisStuAnswer = InforDifficultReview.getQueList().get(i).getStuAnswer();
                thisAnswer = InforDifficultReview.getQueList().get(i).getAnswer();
                thisStuAssess = InforDifficultReview.getQueList().get(i).getStuAssess();
                if(!thisStuAssess.equals("")) {
                    if (thisStuAssess.equals("正确") || thisStuAssess.equals("优秀")|| thisStuAssess.equals("一般")) {
                        totalItemCountTrue++;
                    }
                }else {
                    if (thisStuAnswer.equals(thisAnswer)) {
                        totalItemCountTrue++;
                    }
                }

                if(!thisStuAnswer.equals("")||!thisStuAssess.equals("")){
                    quesAnsweredItemCount++;
                }

            }

            InforDifficultReview.setStuAnswerNewAll(stuAnswerAll);
            InforDifficultReview.setStuAssessNewAll(stuAssessAll);
            InforDifficultReview.setCorrectRate(Control.getCorrectRate(Float.valueOf(totalItemCountTrue),Float.valueOf(totalItemCount)));
            InforDifficultReview.setAnsweredItemCount(quesAnsweredItemCount);
        }else if(ModelFrom==PaperDef.FROM_GUESS_REVIEW){
            InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(position).setStuAssess(stuAssess);

            int totalItemCount = InforGuessTesting.getPaperContent().get(PaperID).getTotalItemCount();
            String stuAnswerAll = "";
            String stuAssessAll = "";
            double totalScore = 0;
            String thisStuAnswer = "";
            String thisAnswer = "";
            String thisStuAssess = "";
            int quesAnsweredItemCount = 0;
            for(int i=0;i<totalItemCount;i++){
                if(i==0){
                    stuAnswerAll = InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(i).getStuAnswer();
                    stuAssessAll = InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(i).getStuAssess();
                }else{
                    stuAnswerAll = stuAnswerAll+"#$*#"+InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(i).getStuAnswer();
                    stuAssessAll = stuAssessAll+"#$*#"+InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(i).getStuAssess();
                }
                thisStuAnswer = InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(i).getStuAnswer();
                thisAnswer = InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(i).getAnswer();
                thisStuAssess = InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(i).getStuAssess();
                if(!thisStuAssess.equals("")) {
                    totalScore = totalScore+Double.valueOf(thisStuAssess);
                }else {
                    if (thisStuAnswer.equals(thisAnswer)) {
                        totalScore = totalScore+Double.valueOf(score/totalItemCount);
                    }
                }

                if(!thisStuAnswer.equals("")||!thisStuAssess.equals("")){
                    quesAnsweredItemCount++;
                }

            }

            InforGuessTesting.getPaperContent().get(PaperID).setStuAnswerNewAll(stuAnswerAll);
            InforGuessTesting.getPaperContent().get(PaperID).setStuAssessNewAll(stuAssessAll);
            InforGuessTesting.getPaperContent().get(PaperID).setCorrectRate(Control.getCorrectRate((float) totalScore, (float) score));
            InforGuessTesting.getPaperContent().get(PaperID).setAnsweredItemCount(quesAnsweredItemCount);
        }else if(ModelFrom==PaperDef.FROM_BASE_REVIEW_WRONG||ModelFrom==PaperDef.FROM_DIFFERENT_REVIEW_WRONG){

            InforWrongQues.get(PaperID).getQueList().get(position).setStuAssess(stuAssess);

            int totalItemCount = InforWrongQues.get(PaperID).getTotalItemCount();
            String stuAnswerAll = "";
            String stuAssessAll = "";
            int totalItemCountTrue = 0;
            String thisStuAnswer = "";
            String thisAnswer = "";
            String thisStuAssess = "";
            int quesAnsweredItemCount = 0;
            for(int i=0;i<totalItemCount;i++){
                if(i==0){
                    stuAnswerAll = InforWrongQues.get(PaperID).getQueList().get(i).getStuAnswer();
                    stuAssessAll = InforWrongQues.get(PaperID).getQueList().get(i).getStuAssess();
                }else{
                    stuAnswerAll = stuAnswerAll+"#$*#"+InforWrongQues.get(PaperID).getQueList().get(i).getStuAnswer();
                    stuAssessAll = stuAssessAll+"#$*#"+InforWrongQues.get(PaperID).getQueList().get(i).getStuAssess();
                }
                thisStuAnswer = InforWrongQues.get(PaperID).getQueList().get(i).getStuAnswer();
                thisAnswer = InforWrongQues.get(PaperID).getQueList().get(i).getAnswer();
                thisStuAssess = InforWrongQues.get(PaperID).getQueList().get(i).getStuAssess();
                if(!thisStuAssess.equals("")) {
                    if (thisStuAssess.equals("正确") || thisStuAssess.equals("优秀")|| thisStuAssess.equals("一般")) {
                        totalItemCountTrue++;
                    }
                }else {
                    if (thisStuAnswer.equals(thisAnswer)) {
                        totalItemCountTrue++;
                    }
                }

                if(!thisStuAnswer.equals("")||!thisStuAssess.equals("")){
                    quesAnsweredItemCount++;
                }

            }

            InforWrongQues.get(PaperID).setStuAnswerNewAll(stuAnswerAll);
            InforWrongQues.get(PaperID).setStuAssessNewAll(stuAssessAll);
            InforWrongQues.get(PaperID).setCorrectRate(Control.getCorrectRate(Float.valueOf(totalItemCountTrue),Float.valueOf(totalItemCount)));
            InforWrongQues.get(PaperID).setAnsweredItemCount(quesAnsweredItemCount);

        }

        if(ModelFrom!=PaperDef.FROM_GUESS_REVIEW) {
            if (stuAssess.equals("正确")) {
                RateFill[position].RbTrue.setChecked(true);
                RateFill[position].RbFalse.setChecked(false);
            } else if (stuAssess.equals("错误")) {
                RateFill[position].RbTrue.setChecked(false);
                RateFill[position].RbFalse.setChecked(true);
            } else if (stuAssess.equals("")) {
                RateFill[position].RbTrue.setChecked(false);
                RateFill[position].RbFalse.setChecked(false);
            }
        }

    }

}